import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import 'winston-daily-rotate-file';
import { ConfigService } from '@nestjs/config';
import { AllExceptionFilter } from './common/filters/all-exception.filter';
import { ValidationPipe, VERSION_NEUTRAL, VersioningType } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService = app.get(ConfigService);
  const port = configService.get<number>('PORT', 3000);
  // 配置日志
  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
  // 为所有注册的路由设置一个全局前缀
  const prefix = configService.get<string>('PREFIX', '/api');
  app.setGlobalPrefix(prefix);
  // 设置全局捕获错误过滤器
  const errorFilterFlag = configService.get<string>('ERROR_FILTER');
  if (errorFilterFlag === 'true') {
    const httpAdapter = app.get(HttpAdapterHost);
    app.useGlobalFilters(new AllExceptionFilter(httpAdapter));
  }
  // 全局管道过滤器
  app.useGlobalPipes(new ValidationPipe({
    // whitelist: true // 去除在类上不存在的字段
  }));
  // cors
  const cors = configService.get<string>('CORS', 'false');
  if (cors === 'true') {
    app.enableCors({
      origin: '*',
      methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
      preflightContinue: false,
    });
  }
  // version
  const versionStr = configService.get<string>('VERSION');
  if (versionStr !== 'undefined') {
    const version = (versionStr ?? '').split(',');
    app.enableVersioning({
      type: VersioningType.URI,
      defaultVersion:
        typeof versionStr === 'undefined' ? VERSION_NEUTRAL : version, // VERSION_NEUTRAL 表示不使用版本号
    });
  }
  // 启动端口
  console.log(`http://localhost:${port}`);
  await app.listen(port);
}

bootstrap();
